#coding=utf-8
#!/usr/bin/python

'''
Created on 2012-11-17

@author: Neo.Chen
'''

'''
功能：
'''
import os
import sys
sys.path.append("../")
import time
import string
import psutil,time

def getProcessInfo(p):
    """取出指定进程占用的进程名，进程ID，进程实际内存, 虚拟内存,CPU使用率
    """
    try:
        cpu = int(p.get_cpu_percent(interval=0))
        rss, vms = p.get_memory_info()
        name = p.name
        pid = p.pid
    #except psutil.error.NoSuchProcess:
    except:
        name = "Closed_Process"
        pid = 0
        rss = 0
        vms = 0
        cpu = 0
    return [name.upper(), pid, rss, vms, cpu]

#抄自http://blog.chinaunix.net/uid-324919-id-96904.html
def getAllProcessInfo():
    """取出全部进程的进程名，进程ID，进程实际内存, 虚拟内存,CPU使用率
    """
    instances = []
    all_processes = list(psutil.process_iter())

    for proc in all_processes:
        try:
            proc.get_cpu_percent(interval=0)
        except:
            print("this is a except. getAllProcessInfo")    #实践中发现上面这个语句经常异常，这里加处理
            pass
    #此处sleep1秒是取正确取出CPU使用率的重点
    time.sleep(1)
    for proc in all_processes:
        instances.append(getProcessInfo(proc))
    return instances

#判断进程是否出现cpu异常
def isProcCpuWarning(process_name, min_cpu, max_cpu):
    warn_cpu = 0
    all_processes = []
    all_processes = getAllProcessInfo()
    #将目标进程名字改为大写，因为ps模块出来的信息也是大写的
    process_name_upper = process_name.upper()
    #接着判断
    haveWarn = False    #是否有cpu警报
    procExist = False   #进程是否存在
    for proc in all_processes:
        #proc获得的信息是大写的，例如['XFTP.EXE', 6124, 2285568, 12521472, 0]
        if proc[0] == process_name_upper:
            print(proc, "obj:", process_name_upper)
            procExist = True
            cpu = 0
            try:
                if len(proc) == 5:
                    cpu = proc[4]
            except:
                print("this is a except.")
                pass
            #打印实际的cpu数值
            print(process_name_upper, ' cpu is:', cpu)
            #判断是否超标了
            if cpu > max_cpu:
                haveWarn = True
                warn_cpu = cpu
            if cpu < min_cpu:
                haveWarn = True
                warn_cpu = cpu
    if procExist <> True :
        haveWarn = True
        print(process_name_upper, ' non-exist ')
    return (haveWarn,warn_cpu)

def main():
    if len(sys.argv) > 1:
        process_name = sys.argv[1]
        min_cpu = string.atoi(sys.argv[2])
        max_cpu = string.atoi(sys.argv[3])
        (haveWarn,warn_cpu) = isProcCpuWarning(process_name, min_cpu, max_cpu)
        print("haveWarn:", haveWarn, "warn_cpu:", warn_cpu)
    else:
        print("cmd line param: vcs_test 0 90")


if __name__ == '__main__':
    main()


